import yzService from "components/ui_components/yz_service";
import yzSpecs from "components/ui_components/yz_specs";
export default {
  components: {
    yzService,
    yzSpecs
  },
  data() {
    return {
      showPage: false,
      locationStatus: false, //定位开关
      activeNames: [],
      query: {
        longitude: "",
        latitude: "",
        id: "",
        basic_info: 1
      },
      lately: [], //飘窗滚动数据
      optionId: 0, //规格ID
      total: 1,
      favorite: false, //收藏开关
      goodsActive: 0,
      beginStatus: 1, //商品售卖状态
      aroundGoods: {},
      count: "",
      shopAddress: {},
      getGoods: {},
      now: "",
      productIndex: 0,

      goodsOptionOpen: false,

      //客服插件
      serviceShow: false,
      serviceQRcode: "",
      serviceMobile: "",
      cservice: "",
      presentTime: "", //获取本地时间
      plugin_setting: {},
      description:'',
      goodsDesc:'',
      height:500,
      popupSpecs: false, //是否开启规格弹窗
      pattern: /^(https?:\/\/)/
    };
  },
  filters: {
    kmUnit(value) {
      let val = parseInt(value);
      let v;
      if (typeof val === "number" && !isNaN(val)) {
        if (val >= 1000) {
          v = (val / 1000).toFixed(2) + "km";
        } else {
          v = val + "m";
        }
      } else {
        v = "0m";
      }
      return v;
    }
  },
  created() {
    this.initData();
    this.now = new Date(this.timestampToTime(new Date().valueOf() / 1000)).valueOf() / 1000;
    this.presentTime = new Date().getTime();
    this.query.id = Number(this.$route.query.goodsId);
    this.query.longitude = this.$route.query.longitude;
    this.query.latitude = this.$route.query.latitude;
    if(this.query.latitude  && this.query.latitude) {
      this.goodsdetails();
    } else {
      this.fun
      .getLocation()
      .then(res => {
        let p = this.fun.bd_encrypt(res.point.lng, res.point.lat);
        this.query.latitude = p.lat;
        this.query.longitude = p.lng;
        this.locationStatus = true;
          this.goodsdetails();
      })
      .catch(err => {
        console.log(err);
        this.goodsdetails();
        this.locationStatus = false;
      });
    }
    
    
    this.serviceDetail();
  },
  methods: {
    initData(){
      this.showPage = false;
      this.getGoods = {};
    },
    goodsOption() {
      $http.post("plugin.travel-around.frontend.goods.option", { goods_id: this.query.id }, "加载中..").then(response => {
        //区别商品是否可售
        if (response.result == 1) {
          let res = response.data;
          this.categoriesGoodsList = res;
          this.getArrEqual(res, this.getGoods.has_many_options);
        } else {
          this.$dialog.alert({
            message: response.msg
          });
        }
      });
    },
    getArrEqual(arr1, arr2) {
      //周边游供应链的商品，plugin.jd-supply.frontend.goods.option接口返回为1的才去取库存，返回为0的就库存直接是0
      if (arr1 === null) {
        this.beginStatus = -1;
        return;
      }
      let that = this;
      for (let i = 0; i < arr2.length; i++) {
        if (arr1[arr2[i].id] == 0) {
          that.getGoods.has_many_options[i].stock = 0;
        }
      }
    },
     //点击关闭 clicktype为1：确认按钮 ，为0：关闭弹窗操作
    close_yz_specs_popup(_optionsId, goodsCount, clicktype, cardId, optionsMaxCount, level_id, option_level_id) {
      if(clicktype == 1 && this.aroundGoods.ecommerce === 0) {
        if(goodsCount > this.aroundGoods.singleMax) {
          this.$toast('商品数量已超出购买最大数量');
          return false;
        }
        if(goodsCount < this.aroundGoods.singleMin) {
          this.$toast('商品数量少于最小购买数量');
          return false;
        }
        this.$router.push(
          this.fun.getUrl(
            "goodsorder",
            {},
            {
              goodsId: this.query.id,
              optionsId: _optionsId,
              total: goodsCount,
              tag: "tourAround",
              orderShowDate: this.aroundGoods.orderShowDate
            }
          )
        );
      }
      this.popupSpecs = false;
    },
    timestampToTime(timestamp) {
      if (!timestamp) return;
      var date = new Date(Number(timestamp)); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      let Y = date.getFullYear() + "/";
      let M = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "/";
      let D = this.change(date.getDate()) + " ";
      let h = this.change(date.getHours()) + ":";
      let m = this.change(date.getMinutes());

      // let s = this.change(date.getSeconds());
      return Y + M + D + h + m;
    },
    points(backTime) {
      let disposeTime = new Date(backTime).getTime();
      if(disposeTime <= 0) return false
      // let disposeTime = new Date(new Date(TimeDate).toLocaleDateString()).getTime();
      let date1 = new Date(new Date().toLocaleDateString()).getTime();
      return date1 === Number(disposeTime) ? true : false;
    },
    computingTime(afterTime, backTime) {
      let compTime = new Date(afterTime).getTime();
      let endTime = new Date(backTime).getTime();
      if (!Number(endTime)) return;
      let res = Number(compTime) - Number(endTime);
      if (res === 0) {
        this.beginStatus = 2;
        return true;
      }
      if (res > 0) {
        this.beginStatus = 2;
        return true;
      } else {
        return false;
      }
    },
    beforeDay(time) {
      let untilTime = new Date(time).getTime();
      if (!Number(untilTime)) return;
      return untilTime - Number(this.presentTime);
    },
    afterTimeData(time) {
      let afterTime = new Date(time).getTime();
      if (afterTime <= 0) return;
      return afterTime - Number(this.presentTime);
    },
    navigation(...params) {
      let [latitude, longitude, storeName] = [...params];
      let point = this.fun.bd_decrypt(longitude, latitude);
      this.fun.goToWXAdress(point, storeName);
    },
    callStore(phone) {
      window.location.href = "tel://" + phone;
    },
    tapIndex() {
      //首页跳转
      this.$router.replace(this.fun.getUrl("travelIndex", {}, {}));
    },
    storeNav() {
      this.$router.push(this.fun.getUrl("tourAroundStoreList", {}, { goodsId: this.query.id, latitude: this.query.latitude, longitude: this.query.longitude }));
    },
    clickChat() {
      this.serviceShow = true;
    },
    serviceDetail() {
      $http.post("goods.customer-service.index", { goods_id: this.query.id }, "正在获取").then(
        response => {
          if (response.result == 1) {
            let res = response.data;
            this.cservice = res.cservice;
            this.serviceQRcode = res.service_QRcode;
            this.serviceMobile = res.service_mobile;
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        },
        function(response) {
          console.log(response);
        }
      );
    },
    onFavorite() {
      let favorite = !this.favorite;
      let api = "";
      if (favorite) {
        api = "member.member-favorite.store";
      } else {
        api = "member.member-favorite.destroy";
      }
      $http.get(api, { goods_id: this.query.id }, "正在获取").then(
        response => {
          if (response.result == 1) {
            this.favorite = favorite;
            this.$toast(response.msg);
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        },
        function(response) {
          // console.log(response);
          // error callback
        }
      );
    },
    adjustIframe() {
      if(this.aroundGoods?.content.match(this.pattern)) {
        // window.location.replace(this.aroundGoods?.content);
        console.log(this.$refs.iframe.contentWindow);
        this.$nextTick(() => {
          this.height = this.$refs.iframe.document.documentElement.clientHeight;
          // this.height = this.$refs.iframe.contentWindow.document.documentElement.scrollHeight;
        });
      }
    },
    goodsdetails() {
      $http.post("goods.goods.get-goods-page", this.query, "加载中..").then(response => {
        if (response.result == 1) {
          let res = response.data;
          this.shopAddress = res.plugin?.travel_around.data?.shop_address;
          this.aroundGoods = res.plugin?.travel_around.data?.travel_around_goods;
          
          if(this.aroundGoods?.content.match(this.pattern)) {
            this.$nextTick(() => {
              this.height = this.$refs.iframe.contentWindow.document.documentElement.scrollHeight;
            });
          }
          this.description = this.aroundGoods?.content?.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;"'); 
          this.count = res.plugin?.travel_around.data?.count;
          this.getGoods = res.get_goods;
          this.goodsDesc =this.getGoods?.content?.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;"'); 
          this.lately = res.plugin?.travel_around.data?.lately;
          this.optionId = this.getGoods.has_many_options[0].id;
          this.plugin_setting = response.basic_info?.plugin_setting;
          let nowtime = new Date().getTime();
          let beginTime = new Date(this.aroundGoods.beginTime).getTime();
          if (beginTime > nowtime) {
            //活动是否开售
            this.beginStatus = 0;
          }
          if (res.is_favorite) {
            this.favorite = res.is_favorite.status == 1 ? true : false;
          }
          if (this.plugin_setting.travel_around.is_ios_sell === 1 || this.plugin_setting.travel_around.is_ios_sell === "1") {
            // 卡券商品 并开启 IOS禁用
            if (this.fun.isIosOrAndroid() === "ios") {
              this.beginStatus = -1;
            }
          }
          this.$nextTick(() => {
            this.fun.wxShare(
              "",
              { mid: this.fun.getKeyByMid() },
              {
                link: window.location.href,
                title: this.getGoods.title,
                imgUrl: this.getGoods.thumb,
                description:  this.aroundGoods.long_title || ''
              }
            );
          },50)
          this.goodsOption();
          this.showPage = true;
        } else {
          this.$dialog.alert({
            message: response.msg
          }).then(() => {
            this.$router.go(-1);
          });
        }
      });
    },
    onPreorder() {
      if (this.aroundGoods.ecommerce === 0) {
        this.popupSpecs = true;
        return false;
        this.$router.push(
          this.fun.getUrl(
            "goodsorder",
            {},
            {
              goodsId: this.query.id,
              optionsId: this.optionId,
              total: this.total,
              tag: "tourAround",
              orderShowDate: this.aroundGoods.orderShowDate
            }
          )
        );
      }
    },
    goodsLikeOn(id) {
      this.$router.push(this.fun.getUrl("goods", { id: id }));
    },
    change(t) {
      if (t < 10) {
        return "0" + t;
      } else {
        return t;
      }
    }
  }
};
